package kr.or.ddit.web.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.inject.Inject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kr.or.ddit.member.service.IMemberService;

import kr.or.ddit.member.service.IMemberService.memberResult;

import kr.or.ddit.vo.MemberDTO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/member/*")
public class MemberController {
	@Inject
	private IMemberService service;

	public IMemberService getService() {
		return service;
	}

	public void setService(IMemberService service) {
		this.service = service;
	}

	@RequestMapping("memberForm.do")
	public String memberForm() {
		return "member/memberForm";
	}
	
	@RequestMapping("memberView.do")
	public String memberView(Model model, HttpSession session){

		String mem_id = (String)session.getAttribute("idInSession");
		MemberDTO member = service.getMember(mem_id);
		model.addAttribute("member",member);
		return "member/memberView";
	}
	
	@RequestMapping("memberEditForm.do")
	public String memberEditForm(Model model, HttpSession session){

		String mem_id = (String)session.getAttribute("idInSession");
		MemberDTO member = service.getMember(mem_id);
		model.addAttribute("member",member);
		return "member/memberEdit";
	}

	@RequestMapping("memberInsert.do")
	public String buyerInsert(@ModelAttribute("member") MemberDTO member,
			Model model) throws UnsupportedEncodingException {

		memberResult result = service.createMember(member); 

		String msg = null;
		String viewName = null;

		if (result == memberResult.OK) {
			msg = URLEncoder.encode("정상가입 처리 되었습니다.", "UTF-8");
			viewName = "redirect:/index.jsp?msg=" + msg;
		} else if (result == memberResult.PKDuplicated) {
			msg = "중복된 아이디가 존재 합니다 다른아이디를 입력해주세요";
			model.addAttribute("msg", msg); 
			viewName = "member/memberForm";
		} else {
			msg = "서버측 오류 발생!! 잠시뒤 다시 등록해주세요";
			model.addAttribute("msg", msg);
			viewName = "member/memberForm";
		}
		return viewName;
	}
	
	
	
	@RequestMapping("memberEdit.do")
	public String upadate(@ModelAttribute("member") MemberDTO member, Model model, HttpServletResponse response) throws IOException{
		memberResult result = service.modifyMember(member);
	
		String msg = null;
		String viewName = null;
		
		if(result == memberResult.OK){
			msg = URLEncoder.encode("수정이 정상 처리 됐음", "UTF-8");
//			redirect: 사용하면 뷰 리절버가 알아서 CP를 붙여줌
			viewName = "redirect:/member/memberView.do?mem_id="
						+member.getMem_id()+"&msg="+msg;
			
		}else if(result == memberResult.Failed){
			msg = "알수없는 이유로 수정에 실패ㅠ.ㅠ.ㅠ 쫌 있다 다시 해봐요.";
			model.addAttribute("msg", msg);
			viewName="member/memberEdit";
			
		}else if(result == memberResult.NOTEXIST){
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "정상적인 루트를 타지 않았네요.");
			return null;
		}else if(result == memberResult.INVALIDPASSWORD){
			msg = "비밀번호 오류";
			model.addAttribute("msg", msg);
			viewName ="member/memberEdit";
		}
		return viewName;
		
	}
	
	

	@RequestMapping("login.do")
	public String login(@ModelAttribute("member") MemberDTO member,
			HttpServletRequest request, HttpServletResponse response,
			Model model, HttpSession session) throws UnsupportedEncodingException {
		String mem_id = request.getParameter("mem_id");
		String mem_passwd = request.getParameter("mem_passwd");

		memberResult result = service.loginchk(mem_id, mem_passwd);

		String msg = "";
		String viewName = null;

		if (StringUtils.isNotBlank(mem_id)
				&& StringUtils.isNotBlank(mem_passwd)) {

			if (result == memberResult.OK) {
				Cookie idCookie = new Cookie("saveId", mem_id);
				int expiry = 0;
				String idCheck = request.getParameter("idCheck"); 
				
				if (StringUtils.isNotBlank(idCheck)) {
					expiry = 60 * 60 * 24 * 7;
				}
				idCookie.setPath("/"); 
				idCookie.setMaxAge(expiry); 
				response.addCookie(idCookie); 
				session.setAttribute("idInSession", mem_id);
				
				msg = URLEncoder.encode(mem_id + "님 환영합니다.", "UTF-8");
				model.addAttribute("msg", msg);
				viewName = "redirect:/index.jsp";
			} else if (result == memberResult.INVALIDPASSWORD) {
				msg = URLEncoder.encode("비밀번호오류  실패~!!! 실패!!", "UTF-8");
				model.addAttribute("msg", msg);
				viewName = "redirect:/index.jsp";
			} else {
				msg = URLEncoder.encode("니 머 빼묶고 썻데이.. 잘봐라!", "UTF-8");
				model.addAttribute("msg", msg);
				viewName = "redirect:/index.jsp";
			}
		}
		return viewName;
	}
	
	@RequestMapping("logout.do")
	public String logout(HttpSession session){
		session.invalidate();
		return "redirect:/index.jsp";
	}
}
